<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag,
  NSwitch,
  NFlex,
  NAvatar,
  NSelect,
  NImage,
  NDataTable,
  NIcon,
  NTooltip,
  NPopover
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '报销记录' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'
const message = useMessage()
const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '报销记录',
  initForm: {},
  doCreate: api.createBaoXiao,
  doUpdate: api.updateBaoXiao,
  doDelete: api.deleteBaoXiao,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  xms:[],
  users:[],
  uploadAction: base_path + 'api/baoxiao/baoxiao_list/file',
  token: getToken(),
  state_option: [
    {
      value:0,
      label:"待审核"
    },{
      value:1,
      label:"已审核"
    },{
      value:2,
      label:"驳回"
    }],
})
const deptOption = ref([])

onMounted(() => {
  api.getBaoXiaoXms().then((res) => (data.xms = res.data))
  api.getUsers().then((res) => (data.users = res.data))
  api.getDeptsTree().then((res) => (deptOption.value = res.data))
  $table.value?.handleSearch()
})

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

const columns = [
  {
    title: '+',
    width: 60,
    key: 'details',
    align: 'center',
    type: 'expand',
    expandable: (row) => row.details !== null,
    renderExpand: (row) => {
      let details = row.details ?? []
      let details_columns = [
        {
          width: 'auto',
          title: '日期',
          key: 'add_date',
        },
          {
          width: 'auto',
          title: '项目',
          key: 'xm_name',
        },
        {
          width: 'auto',
          title: '金额',
          key: 'price',
        },
          {
          width: 'auto',
          title: '发票金额',
          key: 'fp_price',
        },
        {
          width: 'auto',
          title: '备注',
          key: 'desc',
        },
        {
          width: '80',
          title: '发票',
          key: 'pic1',
          render(row2) {
            let image = row2.pic1[0]
            if (!image) {
              image = default_image
            }
            return h(NFlex, {}, [
              h(NImage, {
                src: image.url,
                width: 30,
                fallbackSrc: default_image,
                style: {
                  borderRadius: '5px'  // 使图片变为圆形
                }
              }),
            ])
          },
        },
        {
        width: "auto",
        title: '凭证',
        key: 'pic2',
        render(row2) {
          let images = row2.pic2 || [];  // 如果没有 pic1 数据，默认为空数组
          if (images.length === 0) {
            images = [default_image];  // 如果没有图片，使用默认图片
          }
          // 渲染图片
          return h(NFlex, { wrap: 'wrap' },  // 使用 wrap: 'wrap' 让图片能够换行显示
            images.map(image =>
              h(NImage, {
                src: image.url || default_image,  // 如果图片地址为空，则使用默认图片
                width: 30,  // 图片的宽度
                height: 30, // 图片的高度
                fallbackSrc: default_image,  // 加载失败时使用的默认图片
                style: {
                  borderRadius: '2px',  // 圆角样式
                }
              })
            )
          );
        },
      }



      ]
      return h(NDataTable, {
        columns: details_columns,
        striped: true,
        size: 'small',
        data: details,
        style: { width: '1000px', margin: '10px 10px' },
      })
    },
  },
  {
    title: 'ID',
    key: 'id',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '报销部门',
    key: 'bm_name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '报销人',
    key: 'user_name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '单号',
    key: 'no',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  }, {
    title: '报销金额',
    key: 'price',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  }, {
    title: '发票金额',
    key: 'fp_price',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  }, {
    title: '发票差额',
    key: 're_price',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },

  {
    title: '状态',
    key: 'status_name',
    width: '100',
    align: 'center',
    fixed: 'right',
    render(row) {
      let type = 'primary'; // 默认主色

      let popoverContent = ''; // 用于存放提示文本

      if (row.status === 0) {
        type = 'warning'; // 状态为0时，警告色
      }
      let icon =  h(
          NTag,
          { type: type, size: 'small', bordered: false, style: { margin: '4px 3px' } },
                { default: () => row.status_name },
      );

      if (row.status === 2) {
        type = 'error'; // 状态为2时，错误色
        popoverContent = row.bh_desc; // 图标的提示内容
        icon =  h(
                  NTag,
                  { type: type, size: 'small', bordered: false, style: { margin: '4px 3px', } },
                        { default: () => [
                            row.status_name,
                            h(NIcon, renderIcon('material-symbols:shield-question-outline-rounded', { size: 14 })), // 这里添加图标
                  ] },
              );
      }


      return h(
          'div',
          { style: { display: 'flex', alignItems: 'center', justifyContent: 'center' } },
          [
            row.status === 2 // 仅当 icon 存在时，才渲染 NPopover
                ? h(
                    NPopover,
                    { content: popoverContent, trigger: 'hover' },
                    {
                      trigger: () =>icon,
                      default: () => popoverContent,
                    }
                )
                : icon
          ]
      );
    }
  }


  ,
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: '180',
    align: 'center',
    fixed: 'right',
    render(row) {
      if(row.status!==1){
        return [
          withDirectives(
              h(
                  NButton,
                  {
                    size: 'small',
                    type: 'primary',
                    style: 'margin-right: 8px;',
                    onClick: () => {
                      handleEdit(row)
                    },
                  },
                  {
                    default: () => '编辑',
                    icon: renderIcon('material-symbols:edit', { size: 16 }),
                  }
              ),
              [[vPermission, 'post/api/baoxiao/baoxiao_list/update']]
          ),
          h(
              NPopconfirm,
              {
                onPositiveClick: () => handleDelete({data_id: row.id}, false),
                onNegativeClick: () => {
                },
              },
              {
                trigger: () =>
                    withDirectives(
                        h(
                            NButton,
                            {
                              size: 'small',
                              type: 'error',
                            },
                            {
                              default: () => '删除',
                              icon: renderIcon('material-symbols:delete-outline', {size: 16}),
                            }
                        ),
                        [[vPermission, 'delete/api/baoxiao/baoxiao_list/delete']]
                    ),
                default: () => h('div', {}, '确定删除该数据吗?'),
              }
          ),
        ]
      }
    },
  },
]
const validateAddUser = {
  user_id: [
    {
      required: true,
      message: '请选择报销人',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
  bm_id: [
    {
      required: true,
      message: '请选择报销部门',
      trigger: ['input', 'blur', 'change'],
      type: 'number',
    },
  ],
}

const datetimeRange = ref()
function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

let currentDate = new Date();
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // 月份从0开始，所以需要加1
let day = currentDate.getDate();
let formattedDate = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`;

const onCreate_gg = () => {
  return {
    add_date: formattedDate,
    xm_id: 1,
    price: 0,
    desc: '',
    pic1: [],
    fp_price: 0,
    pic2: [],
  }
}
const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  console.log(data)
  if (data.code === 200) {
    file.url = data.data.url
    // 判断 URL 是否以 .png 结尾,上传pdf服务器是自动转成pnd返回
    if (file.url.toLowerCase().endsWith('.png')) {
      file.type = 'image/png'; // 设置文件类型为 PNG
    }
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="报销记录">
    <template #action>
      <div>
        <NButton
            v-permission="'post/api/baoxiao/baoxiao_list/create'"
            class="float-right mr-15"
            type="primary"
            @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          填写报销单
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getBaoXiao"
    >
      <template #queryBar>
        <QueryBarItem label="报销单号" :label-width="80">
          <NInput
              v-model:value="queryItems.no"
              clearable
              type="text"
              style="width: 140px"
              placeholder="请输入报销单号"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>


        <QueryBarItem label="申请时间" :label-width="70">
          <NDatePicker
              v-model:value="datetimeRange"
              type="datetimerange"
              clearable
              placeholder="请选择时间范围"
              @update:value="handleDateRangeChange"
          />
        </QueryBarItem>

        <QueryBarItem label="审核状态" :label-width="80">
          <NSelect
              v-model:value="queryItems.status"
              style="width: 120px"
              :options="data.state_option"
              clearable
              placeholder="全部"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        @save="handleSave"
        style="width: auto;"
    >
      <NForm
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          :model="modalForm"
          :rules="validateAddUser"
      >
        <NFlex >
          <NFormItem label="部门" path="bm_id">
            <NTreeSelect
                v-model:value="modalForm.bm_id"
                :options="deptOption"
                key-field="id"
                label-field="name"
                placeholder="请选择部门"
                clearable
                default-expand-all
                style="width: 170px"
            ></NTreeSelect>
          </NFormItem>
          <NFormItem label="报销人" path="user_id">
            <NSelect
                style="width: 163px"
                v-model:value="modalForm.user_id"
                :options="data.users"
                placeholder="请选择报销人"
            />
          </NFormItem>
          <NFormItem label="报销总额" path="price">
            <n-input style="width: 165px;background: #f4f4f4" v-model:value="modalForm.price"  placeholder="自动计算" readonly/>
          </NFormItem>
          <NFormItem label="发票总额" path="fp_price">
            <n-input style="width: 165px;background: #f4f4f4" v-model:value="modalForm.fp_price"  placeholder="自动计算" readonly/>
          </NFormItem>
        </NFlex>
        <NFormItem label="备注" path="desc">
          <NInput
              style="width: 100%"
              v-model:value="modalForm.desc"
              clearable
              placeholder="请输入备注"
          />
        </NFormItem>

        <n-divider dashed>
          报销详情
        </n-divider>

        <NFormItem label="" path="details">

          <n-layout>
            <n-layout-header>
              <n-flex>
                <n-tag size="large" style="width: 135px"> 日期 </n-tag>
                <n-tag size="large" style="width: 100px"> 报销项目 </n-tag>
                <n-tag size="large" style="width: 80px"> 金额 </n-tag>
                <n-tag size="large" style="width: 200px"> 备注 </n-tag>
                <n-tag size="large" style="width: 60px"> 发票 </n-tag>
                <n-tag size="large" style="width: 80px"> 发票金额 </n-tag>
                <n-tag size="large" style="width: 130px"> 凭证 </n-tag>
              </n-flex>
            </n-layout-header>
            <n-layout-content content-style="padding: 10px 0;">
              <n-scrollbar style="max-height: 260px; ">
              <n-dynamic-input v-model:value="modalForm.details" :on-create="onCreate_gg">
                <template #default="{ value }">

                  <n-flex>

                    <n-date-picker
                        v-model:formatted-value="value.add_date"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="日期"
                        style="width: 135px;"
                        clearable
                        :default-value="formattedDate"
                        size="large"
                      />
                    <NSelect
                        style="width: 100px"
                        v-model:value="value.xm_id"
                        :options="data.xms"
                        placeholder="请选择项目"
                        size="large"
                    />
                    <n-input-number
                        :show-button="false"
                        style="width: 80px"
                        v-model:value="value.price"
                        clearable
                        size="large"
                    />

                    <n-input
                        button-placement="both"
                        v-model:value="value.desc"
                        style="width: 200px"
                    />
                    <n-upload
                        :max="1"
                        style="width: 60px"
                        class="cover"
                        :action="data.uploadAction"
                        :headers="{ token: data.token }"
                        list-type="image-card"
                        @finish="handleFinish"
                        v-model:file-list="value.pic1"

                    ></n-upload>

                    <n-input-number
                        :show-button="false"
                        style="width: 80px"
                        v-model:value="value.fp_price"
                        clearable
                        size="large"
                    />

                    <n-upload
                        :max="10"
                        style="width: auto;"
                        class="cover imgs"
                        :action="data.uploadAction"
                        :headers="{ token: data.token }"
                        list-type="image-card"
                        @finish="handleFinish"
                        v-model:file-list="value.pic2"
                        multiple
                    >
                    </n-upload>


                  </n-flex>

                </template>
              </n-dynamic-input>
              </n-scrollbar>
            </n-layout-content>
          </n-layout>

        </NFormItem>



      </NForm>
    </CrudModal>
  </CommonPage>
</template>
